import React, { PureComponent } from 'react';
import { Upload, Icon, Modal } from 'antd';
import { getBase64 } from '../../utils/utils';
import { getToken } from '../../utils/authority';

interface UploadProps {
  imageLength: number; // 上传几张图片
  handlerChangeImgIds?: (ImgIds: string[]) => void | void; // 获取图片id的数组的方法，返回值为所有id的数组
  handlerChangeImgUrls?: (imageUrls: string[]) => void | void; // 获取图片url的数组的方法，返回值为所有url的数组
  handlerChangeImgAllData?: (imageAllData: object[]) => void | void; // 获取图片所有数据
  ref?: any;
  defaultFileList?: any;
}

interface UploadState {
  fileList: any[];
  previewVisible: boolean;
  previewImage: string;
  defaultFileList: any[];
}

export default class index extends PureComponent<UploadProps, UploadState> {
  state: Readonly<UploadState> = {
    fileList: [],
    previewVisible: false,
    previewImage: '',
    defaultFileList: [],
  };

  static getDerivedStateFromProps(nextProps: any, prevState: any) {
    const { defaultFileList } = nextProps;
    // 当传入的defaultFileList发生变化的时候，更新state
    if (JSON.stringify(prevState.defaultFileList) === '[]') {
      return {
        fileList: defaultFileList,
        defaultFileList,
      };
    }
    // 否则，对于state不进行任何操作
    return null;
  }

  handleCancel = () => this.setState({ previewVisible: false });

  handlePreview = async (file: any) => {
    if (!file.url && !file.preview) {
      // eslint-disable-next-line no-param-reassign
      file.preview = await getBase64(file.originFileObj);
    }

    this.setState({
      previewImage: file.url || file.preview,
      previewVisible: true,
    });
  };

  handleChange = ({ fileList }: any) => {
    // 曹尼玛的煞笔官网。。。害人不浅，深拷贝浅拷贝搞不懂吗？？
    // this.setState({ fileList });
    // 本地组件状态会储存包括上传失败的图片，存的是base64，但是服务器上没有
    this.setState({ fileList: [...fileList] }, () => {
      const okFiles = this.state.fileList.filter((file: any) => file.response);
      if (this.props.handlerChangeImgIds) {
        const okFilesIds = okFiles.map((file: any) => file.response.data.id);
        this.props.handlerChangeImgIds(okFilesIds);
      }
      if (this.props.handlerChangeImgUrls) {
        const okFilesUrls = okFiles.map((file: any) => file.response.data.url);
        this.props.handlerChangeImgUrls(okFilesUrls);
      }
      if (this.props.handlerChangeImgAllData) {
        this.props.handlerChangeImgAllData(okFiles);
      }
    });
  };

  handlerClear = () => {
    this.setState({
      fileList: [],
    });
  };

  handlerReset = () => {
    this.setState({
      fileList: this.props.defaultFileList,
    });
  };

  render() {
    const { previewVisible, previewImage, fileList = [] } = this.state;
    const user = JSON.parse(getToken('adminToken').toString());
    const uploadButton = (
      <div>
        <Icon type="plus" />
        <div className="ant-upload-text">Upload</div>
      </div>
    );

    return (
      <div className="clearfix">
        <Upload
          action="https://api.mlcgxx.cn/admin/images"
          listType="picture-card"
          fileList={fileList}
          headers={{
            Authorization: `Bearer ${user.data.access_token}`,
          }}
          onPreview={this.handlePreview}
          onChange={this.handleChange}
          name="image"
        >
          {fileList.length >= this.props.imageLength ? null : uploadButton}
        </Upload>
        <Modal visible={previewVisible} footer={null} onCancel={this.handleCancel}>
          <img alt="example" style={{ width: '100%' }} src={previewImage} />
        </Modal>
      </div>
    );
  }
}
